<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>音乐数据</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
    <script>
        let musicData = [];
        let currentPage = 1;
        let perPage = 22;  // 默认每页22条数据
        let totalRecords = 0;
        let searchValue = "";

        // 获取音乐数据并渲染
        async function fetchMusicData(page = 1, search = "") {
            try {
                const response = await fetch(`/api/music?page=${page}&per_page=${perPage}&search=${encodeURIComponent(search)}`);
                if (!response.ok) {
                    throw new Error("网络错误");
                }
                const data = await response.json();
                musicData = data.data;
                totalRecords = data.total_records;
                currentPage = data.page;
                perPage = data.per_page;
                renderTable(musicData);
                renderPagination(totalRecords, currentPage, perPage);
            } catch (error) {
                console.error("获取数据失败:", error);
            }
        }

        // 渲染表格
        function renderTable(data) {
            const tableBody = document.getElementById("music-data");
            tableBody.innerHTML = ""; // 清空当前表格内容

            data.forEach(item => {
                const row = document.createElement("tr");
                const date = new Date(item.timestamp * 1000); // 转换时间戳为日期
                row.innerHTML = `
                    <td>${item.id}</td>
                    <td>${date.toLocaleString()}</td>
                    <td>${item.artist}</td>
                    <td>${item.title}</td>
                `;
                tableBody.appendChild(row);
            });
        }

        // 渲染分页控件
        function renderPagination(totalRecords, currentPage, perPage) {
            const pagination = document.getElementById("pagination");
            pagination.innerHTML = ""; // 清空分页内容

            const totalPages = Math.ceil(totalRecords / perPage);  // 总页数
            if (totalPages <= 0) return;  // 如果没有记录，直接返回

            for (let i = 1; i <= totalPages; i++) {
                const li = document.createElement("li");
                li.classList.add("page-item", i === currentPage ? "active" : "inactive"); // 仅在当前页添加 active 类
                li.innerHTML = `<a class="page-link" href="#">${i}</a>`;
                li.addEventListener("click", (event) => {
                    event.preventDefault();
                    fetchMusicData(i, searchValue);
                });

                pagination.appendChild(li);
            }
        }


        // 根据搜索内容过滤数据
        function filterData() {
            searchValue = document.getElementById("search").value;
            fetchMusicData(1, searchValue, perPage);  // 重新请求数据，从第1页开始
        }

        // 监听每页条数变化
        function updatePerPage() {
            const perPageValue = document.getElementById("per-page").value;
            perPage = perPageValue ? parseInt(perPageValue) : 22;
            fetchMusicData(1, searchValue);  // 重新从第一页请求数据
        }

        function sortData() {
            const sortedData = [...musicData].sort((a, b) => a.artist.localeCompare(b.artist));
            renderTable(sortedData);
        }

        function defaultTheme() {
            const body = document.body;

            // 检查 localStorage 中是否保存了模式
            const currentMode = localStorage.getItem("mode");
            if (currentMode) {
                const theme = currentMode;
                if (theme === "light") {
                    body.classList.remove("dark-mode");
                    body.classList.add("light-mode");
                } else if (theme === "dark") {
                    body.classList.remove("light-mode");
                    body.classList.add("dark-mode");
                }
            } else {
                // 跟随系统设置
                if (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches) {
                    body.classList.remove("light-mode");
                    body.classList.add("dark-mode");
                } else {
                    body.classList.remove("dark-mode");
                    body.classList.add("light-mode");
                }
            }
        }

        // 切换主题
        function toggleTheme() {
            let theme = document.getElementById("theme-selector").value;
            const body = document.body;

            if (theme === "light") {
                body.classList.remove("dark-mode");
                body.classList.add("light-mode");
            } else if (theme === "dark") {
                body.classList.remove("light-mode");
                body.classList.add("dark-mode");
            } else {
                // 跟随系统设置
                if (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches) {
                    body.classList.remove("light-mode");
                    body.classList.add("dark-mode");
                } else {
                    body.classList.remove("dark-mode");
                    body.classList.add("light-mode");
                }
            }
        }

        // 页面加载时获取数据
        window.onload = () => {
            defaultTheme();  // 根据系统主题设置初始主题
            fetchMusicData();
        };
    </script>
</head>
<body>
    <div>
        <!-- 主题切换选择框 -->
        <label for="theme-selector"></label>
        <select id="theme-selector" class="theme-toggle pagination btn btn-dark" onchange="toggleTheme()">
            <option value="auto">跟随系统</option>
            <option value="light">浅色模式</option>
            <option value="dark">深色模式</option>
        </select>
    </div>
    <div class="container mt-5">
        <h1 class="mb-4">音乐数据</h1>

        <input type="text" id="search" placeholder="搜索艺术家或标题" class="form-control mb-3" oninput="filterData()">

        <label for="per-page">每页显示条数:</label>
        <input type="number" id="per-page" value="22" class="form-control mb-3" onchange="updatePerPage()">

        <button class="btn btn-primary" onclick="sortData()">按艺术家排序</button>
        <button class="btn btn-secondary" onclick="fetchMusicData()">刷新数据</button>

        <table class="table table-bordered mt-3">
            <thead>
            <tr>
                <th>ID</th>
                <th>日期</th>
                <th>艺术家</th>
                <th>标题</th>
            </tr>
            </thead>
            <tbody id="music-data">
            <!-- 数据将在此处填充 -->
            </tbody>
        </table>
        <!-- 分页控件 -->
        <nav>
            <ul class="pagination" id="pagination">
                <!-- 分页按钮将动态生成 -->
            </ul>
        </nav>
    </div>
</body>
</html>
